﻿#include "unstackplatemanager.h"

#include "systemconfiguration.h"
#include "component_log.h"
#include "componentmanager.h"
#include "unstackplate_data.h"

UnstackPlateManager::UnstackPlateManager(QObject* parent)
	: ComponentBase(parent)
{
	m_name = "拆垛托盘管理组件";
	m_type = Component::component_unstackPlate;
}

UnstackPlateManager::~UnstackPlateManager()
{}
QStringList UnstackPlateManager::GetAllUnstackPlateName()
{
	QStringList names;
	for (auto& iter : m_plates) {
		names.push_back(iter.first);
	}
	return names;
}

UnstackPlate* UnstackPlateManager::GetPlateObject(const QString& id)
{
	if (m_plates.find(id) != m_plates.end()) {
		return m_plates[id];
	}
	log_error("Not find plate id = {}", id);
	return nullptr;
}

void* UnstackPlateManager::GetPoint(const QString& id)
{
	if (m_plates.find(id) != m_plates.end()) {
		return m_plates[id];
	}
	log_error("Not find plate id = {}", id);
	return nullptr;
}


// 组件初始化处理函数
int UnstackPlateManager::ComponentInit()
{
	auto ids = syscfg->GetUnstackplateIds();
	if (ids.size() <= 0) {
		log_trace("Not find any unstackplate, so dont neet create unstack manager");
		return -1;
	}
	// 创建托盘对象
	for (auto& id : ids) {
		auto temp = new UnstackPlate(id);
		QString msg;
		if (temp->Init(msg)) {
			log_trace("unstack plate {} load successed", id);
			m_plates.emplace(id, temp);
			
		} else {
			SetWarningmsg(msg);
			log_error("unstack plate {} load failed", id);
			continue;
		}

	}
	//// 订阅wcs拆垛托盘到位消息
	//auto wcs = m_ob->GetComponent(Component::component_wcsrec);
	//if (wcs == nullptr) {
	//	SetErrmsg("获取wcs组件失败");
	//	return -99;
	//}
	//bool ret = wcs->RegisterSubscriberFunction((int)WCSMsgType::wcs_msg_plate_arrive, [&](const QByteArray& info) {
	//	return OnPlateArrive(info);
	//	});
	//if (!ret) {
	//	SetErrmsg("注册订阅函数失败");
	//	return -99;
	//}
	log_info("unstack plate manager Init success, plate num = {}", m_plates.size());
	return 0;
}
/*自检接口*/
bool UnstackPlateManager::ComponentCheckSelfState()
{

	return true;
}
/*复位接口*/
bool UnstackPlateManager::ComponentSelfReset()
{

	return true;
}

bool UnstackPlateManager::ExcuteCmd(int cmd, const QByteArray& input, QByteArray& output)
{
	if (cmd == 1) {
		QStringList name = GetAllUnstackPlateName();
		output = name.join("-").toUtf8();
		return true;
	}
	return false;
}

using namespace unstackplate;

int UnstackPlateManager::OnPlateArrive(const QByteArray& data)
{
	/*ArriveInfo info = {};
	info.fromJson(data);
	if (info.type() != 2) {
		return -1;
	}
	if (m_plates.find(info.stackPlace()) != m_plates.end()) {
		auto plate = m_plates[info.stackPlace()];
		if (!plate->SetPlateArrived()) {
			SetWarningmsg(QString("设置拆垛托盘[%1]到位失败").arg(info.stackPlace()));
		}
		return 0;
	}*/
	return -1;
}
